package hoodoos.flow;

import com.google.common.base.Strings;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import java.util.Map;
import lombok.ToString;

@ToString
public class FlowCondition implements Comparable<FlowCondition> {

  private final String id;
  private final String conditionScript;
  private Expression conditionExpression = null;
  private final FlowRulesConfigLine flowRulesConfigLine;
  private final boolean noConditions;

  public FlowCondition(FlowRulesConfigLine flowRulesConfigLine) {
    this.flowRulesConfigLine = flowRulesConfigLine;
    this.id = flowRulesConfigLine.getTo();
    this.conditionScript = flowRulesConfigLine.getConditionScript();
    this.noConditions = Strings.isNullOrEmpty(conditionScript);
    if (!noConditions) {
      conditionExpression = AviatorEvaluator.compile(conditionScript, true);
    }
  }

  public boolean evaluate(Map<String, Object> param) {
    return noConditions || (boolean) conditionExpression.execute(param);
  }

  @Override
  public int compareTo(FlowCondition o) {
    return Integer.compare(this.flowRulesConfigLine.getPriority(), o.flowRulesConfigLine.getPriority());
  }

  public String getTo() {
    return flowRulesConfigLine.getTo();
  }
}
